package com.example.writting.ui.cases

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.writting.databinding.ItemCaseBinding

class CaseAdapter(
    private val onCaseClick: (String) -> Unit
) : ListAdapter<CaseItem, CaseAdapter.CaseViewHolder>(CaseDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CaseViewHolder {
        val binding = ItemCaseBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return CaseViewHolder(binding)
    }

    override fun onBindViewHolder(holder: CaseViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    inner class CaseViewHolder(
        private val binding: ItemCaseBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        init {
            binding.root.setOnClickListener {
                val position = adapterPosition
                if (position != RecyclerView.NO_POSITION) {
                    onCaseClick(getItem(position).id)
                }
            }
        }

        fun bind(item: CaseItem) {
            binding.tvTitle.text = item.title
            binding.tvSource.visibility = ViewGroup.GONE
        }
    }

    private class CaseDiffCallback : DiffUtil.ItemCallback<CaseItem>() {
        override fun areItemsTheSame(oldItem: CaseItem, newItem: CaseItem): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: CaseItem, newItem: CaseItem): Boolean {
            return oldItem == newItem
        }
    }
} 